package com.srwl.mytx.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.PersonDonationRecordAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Donation;
import com.srwl.mytx.domain.Forward;
import com.srwl.mytx.service.DonationService;
import com.srwl.mytx.service.ForwardService;
import com.srwl.mytx.widget.NodataFooter;
import com.srwl.mytx.widget.RPTitleBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ReceivedDonationRecordActivity extends BaseActivity implements PersonDonationRecordAdapter.InteractionListener {
    private static final String TAG = "ReceivedForwardRecordAc";
    private RecyclerView rv_forwardRecord;
    private PersonDonationRecordAdapter adapter;
    private ProgressBar progressBar;
    private RPTitleBar titleBar;
    private MaterialSmoothRefreshLayout refreshLayout;
    private List<Donation> donationList = new ArrayList<>();
    private int page = 1;
    private final int SIZE = 10;
    private boolean hasNextPage = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_received_donation_record);
        rv_forwardRecord = findViewById(R.id.rv_forward_record);
        progressBar = findViewById(R.id.progress_bar);
        initTitleBar();
        initRefreshLayout();
        adapter = new PersonDonationRecordAdapter(ReceivedDonationRecordActivity.this, donationList, this);
        rv_forwardRecord.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rv_forwardRecord.setAdapter(adapter);
        loadData(true);
    }
    //必须重新，不然状态栏字体是黑色，，
    protected void setStatusDark(){
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.rp_top_red_color));
    }


    private void initTitleBar() {
        titleBar = findViewById(R.id.title_bar);
        titleBar.setSubTitleVisibility(View.GONE);
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initRefreshLayout() {
        refreshLayout = findViewById(R.id.refresh_layout);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setDisableRefresh(true);
        //  refreshLayout.setEnableHeaderDrawerStyle(false);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setDisableLoadMoreWhenContentNotFull(false);
//        refreshLayout.setOnLoadMoreScrollCallback(new SmoothRefreshLayout.OnLoadMoreScrollCallback() {
//            @Override
//            public void onScroll(View content, float delta) {
//
//                rv_forwardRecord.scrollBy(0, (int) delta);
//            }
//        });
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {

                page = 1;
                loadData(false);
            }

            @Override
            public void onLoadingMore() {

                if (hasNextPage) {
                    loadData(false);
                } else {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onRefreshBegin: 没有更多数据了");
                }
            }

        });
    }

    private void loadData(boolean isFirst) {
        if (!Helper.getInstance().isNetworkConnected()){
            if (!isFirst) refreshLayout.refreshComplete();
            this.showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", SIZE);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .queryReceivedDonations(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();

                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            adapter.showErrorView();
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            adapter.showErrorView();
                            return;
                        }
                        JSONObject pageInfo = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: " + pageInfo.toString());
                        pageInfo.getInteger("total");
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> refreshLayout.setFooterView(new NodataFooter(ReceivedDonationRecordActivity.this)), 2000);
                        }
                        List<Donation> donations = pageInfo.getJSONArray("list").toJavaList(Donation.class);
                        if (donations.size() != 0) {
                            donationList.addAll(donations);
                            adapter.showNormalView();
                            page++;
                        }else if (isFirst){
                            adapter.showNoDataView();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        adapter.showErrorView();
                    }
                });
    }

    @Override
    public void onItemViewClick(String forwardId) {
        toForwardDetail(forwardId);
    }

    void toForwardDetail(String forwardId) {
        if (!Helper.getInstance().isNetworkConnected()){
            this.showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(ForwardService.class)
                .getForwardInfo_v1(forwardId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() && result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        JSONObject jsonObject = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse:获取转赠详情完成 " + jsonObject.toString());
                        Forward fullForward = jsonObject.toJavaObject(Forward.class);
                        startActivity(new Intent(ReceivedDonationRecordActivity.this, ForwardDetailsActivity.class).putExtra(Constant.EXTRA_INFO_FORWARD, fullForward));

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        adapter.showErrorView();
                        showToast(getString(R.string.system_busy));

                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

}
